package com.yksj.healthtalk.ui.chatting;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.handmark.pulltorefresh.library.PullToRefreshBase;
import org.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import org.handmark.pulltorefresh.library.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.core.ImageLoader;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.ObjectHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.ToastUtil;

/**
 * 黑名单
 * @author zhao
 */
public class BlackFriendListActivity extends BaseFragmentActivity implements OnClickListener {
	PullToRefreshListView mRefreshListView;
	ListView mListView;
	UserListAdapter mAdapter;
	PopupWindow mPopupWindow;
	String mGroupId;
	String mUserId;
	Map<Object,Object> mCurrentMaps;
	
	final ObjectHttpResponseHandler mHandler = new ObjectHttpResponseHandler(this) {
		@Override
		public Object onParseResponse(String content) {
			return onParseData(content);
		}
		public void onSuccess(int statusCode, Object response) {
			mAdapter.onDataChange((List<Map<Object,Object>>)response);
			mRefreshListView.onRefreshComplete();
		};
	};
	
	class JoinBlackAsyncHttpResponseHandler extends AsyncHttpResponseHandler{
		final Map<Object,Object> mMap;
		
		public JoinBlackAsyncHttpResponseHandler(Map<Object,Object> map) {
			this.mMap = map;
		}
		@Override
		public void onSuccess(int statusCode, String content) {
			super.onSuccess(statusCode, content);
			if("Y".equalsIgnoreCase(content)){//成功
				mMap.put("isBlack",1);
			}else if("H".equalsIgnoreCase(content)){
				ToastUtil.showShort(getApplicationContext(),"多美币不足");
				mMap.put("isBlack",0);
			}else{//失败
				mMap.put("isBlack",0);
				onFailure(null,null);
			}
			mAdapter.notifyDataSetChanged();
		}
		@Override
		public void onFailure(Throwable error, String content) {
			super.onFailure(error, content);
			ToastUtil.showShort(getApplicationContext(),"加入黑名单失败");
		}
	}
	
	class CancelBlackAsyncHttpResponseHandler extends AsyncHttpResponseHandler{
		final Map<Object,Object> mMap;
		public CancelBlackAsyncHttpResponseHandler(Map<Object,Object> map) {
			this.mMap = map;
		}
		@Override
		public void onSuccess(int statusCode, String content) {
			super.onSuccess(statusCode, content);
			if("Y".equalsIgnoreCase(content)){//成功
				mMap.put("isBlack",1);
				if(isFinishing())mAdapter.notifyDataSetChanged();
			}else if("N".equalsIgnoreCase(content)){
				mMap.put("isBlack",0);
				onFailure(null,null);
			}
			mAdapter.notifyDataSetChanged();
		}
		@Override
		public void onFailure(Throwable error, String content) {
			super.onFailure(error, content);
			ToastUtil.showShort(getApplicationContext(),"取消失败");
		}
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed();
			break;
		case R.id.popup_menu7://加入黑名单
			mCurrentMaps.put("isBlack",1);
			mPopupWindow.dismiss();
			final CustomerInfoEntity infoEntity = (CustomerInfoEntity)mCurrentMaps.get("info");
			HttpRestClient.doHttpJoinBlackList(mGroupId,infoEntity.getId(),new JoinBlackAsyncHttpResponseHandler(mCurrentMaps));
			break;
		case R.id.popup_menu_cancel:
			mPopupWindow.dismiss();
			break;
		}
	}
	
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.black_friend_list_layout);
		
		initView();
		
		mGroupId = getIntent().getStringExtra("groupId");
		mUserId = SmartFoxClient.getLoginUserId();
		
		HttpRestClient.doHttpQueryBlackList(mGroupId,"1","10",mHandler);
	}
	
	private void initView(){
		initTitle();
		
		setBackBtn("返回",this);
		
		setTitle("黑名单");
		
		mRefreshListView = (PullToRefreshListView)findViewById(R.id.pull_refresh_listview);
		mRefreshListView.setOnRefreshListener(new OnRefreshListener2() {
			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
			}
			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				int size = mAdapter.getCount();
				HttpRestClient.doHttpQueryBlackList(mGroupId,"2",size==0?"10":String.valueOf(size),mHandler);
			}
		});
		mListView = mRefreshListView.getRefreshableView();
		mAdapter = new UserListAdapter(getLayoutInflater(),this);
		mListView.setAdapter(mAdapter);
		mRefreshListView.setRefreshing();
	}
	
	private List<Map<Object,Object>> onParseData(String content){
		List<Map<Object,Object>> maps = new ArrayList<Map<Object,Object>>();
		try {
			JSONArray array = new JSONArray(content);
			for (int i = 0; i < array.length(); i++) {
				Map<Object,Object> map = new HashMap<Object, Object>();
				JSONObject jsonObject = array.getJSONObject(i);
				CustomerInfoEntity infoEntity = new CustomerInfoEntity();
				
				String accounts = jsonObject.getString("customerAccounts");
				String nickName = jsonObject.getString("customerNickname");
				String customerid = jsonObject.getString("customerId");
				String header =  jsonObject.getString("clientIconBackground");
				String sex = jsonObject.getString("customerSex");
				int gold = jsonObject.getInt("backGold");
				int black = jsonObject.getInt("customerGroupRel");//0,1,1表示在黑名单
				
				infoEntity.setName(nickName);
				infoEntity.setUsername(accounts);
				infoEntity.setId(customerid);
				infoEntity.setSex(sex);
				infoEntity.setNormalHeadIcon(header);
				
				map.put("gold", gold);
				map.put("isBlack",black);
				map.put("info", infoEntity);
				maps.add(map);
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return maps;
	}
	
	View popupContentV;
	private void onShowPopUpMenu(int golds){
		LayoutInflater inflater = getLayoutInflater();
		if(mPopupWindow == null){
			popupContentV = inflater.inflate(R.layout.window_popup_joinblack_layout, null);
			mPopupWindow = new PopupWindow(popupContentV,LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT,true);
			mPopupWindow.setTouchable(true);
			mPopupWindow.setBackgroundDrawable(new BitmapDrawable());
			mPopupWindow.setOutsideTouchable(true);
			mPopupWindow.setAnimationStyle(R.style.AnimationPreview);
			ViewGroup group = (ViewGroup)popupContentV;
			for (int i = 0; i < group.getChildCount(); i++) {
				group.getChildAt(i).setOnClickListener(this);
			}
			mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
				@Override
				public void onDismiss() {
					mAdapter.notifyDataSetChanged();
				}
			});
		}
		TextView textView = (TextView)popupContentV.findViewById(R.id.gold_txt);
		String note = "加入黑名单,应退回多美币%1$s";
		note = String.format(note,golds);
		textView.setText(note);
		mPopupWindow.setContentView(popupContentV);
		mPopupWindow.showAtLocation(popupContentV, Gravity.BOTTOM, 0, 0);
	}
	
	public class UserListAdapter extends BaseAdapter{
		final Map<String, String> mChoosedMap = new HashMap<String, String>();
		final List<Map<Object,Object>> entities = new ArrayList<Map<Object,Object>>();
		LayoutInflater mInflater;
		Drawable mSexDrawable;
		private final ImageLoader mImageLoader;
		
		public UserListAdapter(LayoutInflater inflater,Context context){
			this.mInflater = inflater;
			this.mImageLoader = ImageLoader.getInstance();
		}
		
		public void onDataChange(List<Map<Object,Object>> list){
			entities.addAll(list);
			notifyDataSetChanged();
		}
		
		public void onChoose(String id,boolean isChoosed){
			if(isChoosed){
				mChoosedMap.put(id,id);
			}else{
				mChoosedMap.remove(id);
			}
		}
		
		@Override
		public int getCount() {
			return entities.size();
		}

		@Override
		public Map<Object,Object> getItem(int position) {
			return entities.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}
		
		public int getGoldSize(int position){
			Map<Object,Object> map = getItem(position);
			int gold = (Integer)map.get("gold");
			return  gold;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			final Map<Object,Object> map = getItem(position);
			final CustomerInfoEntity entity = (CustomerInfoEntity)map.get("info");
			int isBlack = (Integer)map.get("isBlack");
			if(convertView == null){
				holder = new ViewHolder();
				convertView  = mInflater.inflate(R.layout.user_info_item_checkbox_layout,null);
				convertView.setTag(holder);
				holder.headerImageV = (ImageView) convertView.findViewById(R.id.header);
				holder.nameTextV = (TextView) convertView.findViewById(R.id.name);
				holder.sexImageV = (ImageView) convertView.findViewById(R.id.sex);
				holder.levelImageV = (ImageView) convertView.findViewById(R.id.level);
				holder.noteTextV = (TextView) convertView.findViewById(R.id.detail_text);
				holder.chooseBox = (CheckBox)convertView.findViewById(R.id.choose);
			}else{
				holder = (ViewHolder)convertView.getTag();
			}
			
			if(isBlack == 1){//在黑名单中
				holder.chooseBox.setChecked(false);
			}else{
				holder.chooseBox.setChecked(true);
			}
			
			String name = entity.getName();
			String userName = entity.getUsername();
			if(name == null){
				holder.nameTextV.setText(userName);
			}else{
				holder.nameTextV.setText(name+"("+userName+")");
			}
			LevelListDrawable drawable = (LevelListDrawable)holder.sexImageV.getDrawable();
			drawable.setLevel(Integer.valueOf(entity.getSex()));
			holder.noteTextV.setText(entity.getDescription());
			mImageLoader.displayImage(entity.getSex(), entity.getNormalHeadIcon(),holder.headerImageV);
			holder.chooseBox.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					int gold = (Integer)map.get("gold");
					int black = (Integer)map.get("isBlack");//0,1,1表示在黑名单
					mCurrentMaps = map;
					if(black == 0){//加入黑名单
						onShowPopUpMenu(gold);
					}else{
						HttpRestClient.doHttpCancelBlackList(mGroupId,mUserId,new CancelBlackAsyncHttpResponseHandler(map));
					}
				}
			});
			
			return convertView;
		}
	}
	
	private static class ViewHolder{
		ImageView headerImageV;
		TextView nameTextV;
		ImageView sexImageV;
		ImageView levelImageV;
		TextView noteTextV;
		CheckBox chooseBox;
	}
	
}
